import React, { useState, useEffect, useRef, useCallback } from 'react';
import Breadcrumb from 'components/common/Breadcrumb';
import './index.less';
import { Button, Modal, Select, Table, Card, Switch, Tag, Space, message, Spin, Form, Input } from 'antd';
import Area from 'components/Area';
import { FormOutlined, SearchOutlined, RedoOutlined, EditOutlined } from '@ant-design/icons';
import {
    getLiftingControlByArea,
    getAllLiftingControl,
    LiftingControlType,
    IAreaLiftingControl,
    addLiftingControl,
} from 'api/LiftControl';
import { useRequest, useToggle } from 'ahooks';
import { IArea } from 'api/Area';
import { getAllOnlineLiftingControls } from 'api/OnlineLiftingControl';
import { clearGroup } from 'api/LiftingGroup';
import LiftControlEdit from './LiftControlEdit';
import GroupEdit from './GroupEdit';
import { ILiftStatus } from 'api/Lifting';

const formLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
}
const AddPile = () => {
    const [selectedArea, setSelectedArea] = useState(-1); // 选中的区域
    const areaRef: any = useRef();
    const [areaLiftingsControls, setAreaLiftingsControls] = useState<IAreaLiftingControl>(); // 区域内控制箱集合
    const [areaLiftControlsLoading, setAreaLiftControlsLoading] = useState(false);

    const [addModalVisible, setAddModalVisible] = useState(false); // 添加、控制箱弹窗
    const [isEdit, { toggle: toggleIsEdit }] = useToggle(false);
    const [onlineTableVisible, setOnlineTableVisible] = useState(false); // 在线设备表格

    const [groupModalVisible, setGroupModalVisible] = useState(false);

    const [onlineAddModalVisible, setOnlineAddModalVisible] = useState(false);
    const [selectedOnlineDevice, setSelectedOnlineDevice] = useState<any>();
    const [onlinForm] = Form.useForm()

    /** 获取全部区域控制箱 */
    const { data: allLifitngControl, run: getAllLiftingControlRun, loading: getAllLiftControlLoading } = useRequest(
        getAllLiftingControl,
        {
            manual: true,
            formatResult(res) {
                console.log('allControls', res)
                // Object.keys(res.area).forEach((areaId) => {
                //     res.area[areaId] = res.liftings.filter(lift => lift.areaId)
                // })
                return res
            }
        },
    );
    /** 获取主页面区域控制箱 */
    const getLiftControls = useCallback(() => {
        if (selectedArea === -1) {
            getAllLiftingControlRun()
        } else {
            setAreaLiftControlsLoading(true);
            getLiftingControlByArea({ areaId: selectedArea }).then((res) => {
                setAreaLiftControlsLoading(false);
                if (res.groupFlag) {
                    let lifts: any = [];
                    res.group?.map((group) => {
                        lifts = lifts.concat(group.liftings);
                    });
                    res.liftings = lifts;
                }
                setAreaLiftingsControls(res);
            });
        }
    }, [getAllLiftingControlRun, selectedArea]);
    /** 获取区域内的控制箱 */
    useEffect(() => {
        getLiftControls();
    }, [getLiftControls, selectedArea]);
    /** 获取全部在线设备 */
    const { data: allOnlineLiftingContol, run: refreshOnlineLiftingControl, loading: onlineLoading } = useRequest(
        getAllOnlineLiftingControls,
    );

    /** 全部区域时获取全部数量树桩 */
    const getAllLiftingControlNumer = useCallback(() => {
        let res = Object.keys(allLifitngControl?.area || {}).reduce(
            (prev: number, cur: string) => prev + (allLifitngControl?.area[cur] || 0),
            0,
        );
        return res;
    }, [allLifitngControl]);

    /** 表格列 */
    const columns = [
        {
            title: '设备类型',
            dataIndex: 'type',
            key: 'ipAddress',
            render: (type: number) => LiftingControlType[type],
        },
        {
            title: '控制箱IP',
            key: 'ipAddress',
            dataIndex: 'ipAddress',
        },
        {
            title: '在线设备数' + (selectedArea === -1 ? getAllLiftingControlNumer() : ''),
            key: 'onlineNum',
            dataIndex: 'onlineNum',
            width: 200,
        },
    ];
    /** 在线设备表格列 */
    const onlineColumns = [
        {
            title: 'IP',
            dataIndex: 'ipAddress',
        },
        {
            title: '设备类型',
            dataIndex: 'type',
            render: (type: number) => LiftingControlType[type],
        },
        {
            title: '操作',
            render: (row: any, { }) => (
                <Button type="link" disabled={row.addFlag === 1} onClick={() => selectOnlineLiftControlArea(row)}>
                    {row.addFlag === 1 ? '已成功添加' : '添加至管理设备'}
                </Button>
            ),
        },
    ];
    /** 点击添加至管理设备 */
    const selectOnlineLiftControlArea = (liftControl: any) => {
        onlinForm.resetFields()
        setOnlineAddModalVisible(true);
        setSelectedOnlineDevice(liftControl);
        onlinForm.setFieldsValue(liftControl)
    };
    /** 添加在线设备 */
    const addOnlineLiftControl = async () => {
        await onlinForm.validateFields()
        const liftControl = {
            ...selectedOnlineDevice,
            areaId: onlinForm.getFieldValue('areaId')
        };
        addLiftingControl(liftControl).then(() => {
            message.success('添加成功');
            refreshOnlineLiftingControl();
            setSelectedArea(selectedArea);
            setOnlineAddModalVisible(false);
            refreshList()
        });
    };

    /** 编辑控制箱列表 */
    const editLiftingControls = () => {
        setAddModalVisible(true);
        toggleIsEdit(true);
    };

    const refreshList = () => {
        getLiftControls();
        refreshOnlineLiftingControl();
        getAllLiftingControl();
    }

    /** 切换是否分组 */
    const toggleGroup = () => {
        if (areaLiftingsControls?.groupFlag === false) {
            setGroupModalVisible(true);
        } else {
            clearGroup({ areaId: selectedArea }).then(() => {
                message.success('取消分组成功');
                getLiftControls();
            });
        }
    };

    /** 编辑分组 */
    const editGroupInfo = () => {
        setGroupModalVisible(true);
    };

    useEffect(() => {
        if (groupModalVisible === false) {
            getLiftControls();
            getAllLiftingControl();
        }
    }, [groupModalVisible])

    /** 柱子图片 */
    const getLiftImage = (lift: any) => {
        const imageMap: any = {
            [ILiftStatus.down]: (
                <img src={require('assets/imgs/lift-down.png')} className="lifting" alt="" style={{ marginTop: 103 }} />
            ),
            [ILiftStatus.up]: <img src={require('assets/imgs/lift-up.png')} className="lifting" alt="" />,
        };
        return imageMap[lift.liftStatus];
    };
    return (
        <div className="add-pile">
            <Breadcrumb crumbs={['路桩配置', '添加路桩']}></Breadcrumb>
            <Button type="primary" className="mb10" onClick={() => setAddModalVisible(true)}>
                设备添加
            </Button>
            <div className="flex">
                <Area
                    selectedArea={selectedArea}
                    setSelectedArea={setSelectedArea}
                    editable={true}
                    ref={areaRef}
                ></Area>
                <div className="pl20 pr20" style={{ flex: 1 }}>
                    <div className="flex-between mb10">
                        <div className="pl20">设备管理</div>
                        <div className="pr20">
                            <Button size="small" type="text" onClick={editLiftingControls}>
                                <FormOutlined />
                                编辑
                            </Button>
                        </div>
                    </div>
                    <Table
                        className="mb20"
                        rowKey={(record) => record.id}
                        style={{ width: 'calc(100vw - 600px)' }}
                        size="small"
                        loading={getAllLiftControlLoading}
                        dataSource={selectedArea === -1 ? allLifitngControl?.control : areaLiftingsControls?.list}
                        columns={columns}
                        pagination={false}
                        scroll={{ y: 150 }}
                        locale={{ emptyText: '暂无设备' }}
                    />
                    {selectedArea === -1 ? (
                        Object.keys(allLifitngControl?.area || {}).map((areaId) => (
                            <Card hoverable key={areaId} className="area-control-card">
                                <div className="area-name">
                                    {areaRef.current.areas.find((item: any) => item.id == areaId)?.name}
                                </div>
                                <div className="flex lift-items">
                                    {
                                        allLifitngControl?.lifting[areaId].map((lift) => getLiftImage(lift))
                                    }
                                </div>
                            </Card>
                        ))
                    ) : (
                            <Spin spinning={areaLiftControlsLoading}>
                                {areaLiftingsControls?.groupFlag ? (
                                    <Card hoverable className="area-control-card">
                                        <EditOutlined className="edit-group-icon" onClick={editGroupInfo} />
                                        <div className="area-name">
                                            {areaRef.current.areas.find((item: any) => item.id == selectedArea)?.name}
                                        </div>
                                        <div className="flex lift-items">
                                            {areaLiftingsControls?.group?.map((group) => (
                                                <div className="lifting-group" key={group.id}>
                                                    <Tag color="#87d068" className="lifting-group-name">
                                                        {group.name}
                                                    </Tag>
                                                    {group.liftings.map((lift) => (
                                                        <div key={lift.id}>
                                                            <div className="text-center">{lift.orderNum}</div>
                                                            <img
                                                                key={lift.id}
                                                                className="lifting"
                                                                src={
                                                                    lift.liftStatus === 1
                                                                        ? require('assets/imgs/lift-up.png')
                                                                        : require('assets/imgs/lift-down.png')
                                                                }
                                                                alt=""
                                                                style={{ marginTop: lift.liftStatus === 1 ? 0 : 103 }}
                                                            />
                                                        </div>
                                                    ))}
                                                </div>
                                            ))}
                                        </div>
                                    </Card>
                                ) : (
                                        <Card hoverable className="area-control-card">
                                            <div className="area-name">
                                                {areaRef.current.areas.find((item: any) => item.id == selectedArea)?.name}
                                            </div>
                                            <div className="flex lift-items">
                                                {areaLiftingsControls?.liftings?.map((lift) => (
                                                    <div key={lift.id} className="ml10">
                                                        <div className="text-center">{lift.orderNum}</div>
                                                        <img
                                                            className="lifting-control"
                                                            src={
                                                                lift.liftStatus === 1
                                                                    ? require('assets/imgs/lift-up.png')
                                                                    : require('assets/imgs/lift-down.png')
                                                            }
                                                            alt=""
                                                            style={{ marginTop: lift.liftStatus === 1 ? 0 : 103 }}
                                                        />
                                                    </div>
                                                ))}
                                            </div>
                                        </Card>
                                    )}
                                <div className="mt20">
                                    <span className="mr20">分组管控</span>
                                    <Switch
                                        checked={areaLiftingsControls?.groupFlag}
                                        className="mr20"
                                        onClick={toggleGroup}
                                    />
                                    <span style={{ color: 'red' }}>
                                        (系统默认对路桩进行单独控制，通过分组控制对路桩进行自定义分组后，可实现同步操控)
                                </span>
                                </div>
                            </Spin>
                        )}
                </div>
            </div>

            <div className="online-search-tag" onClick={() => setOnlineTableVisible(!onlineTableVisible)}>
                在线设备搜索
                <SearchOutlined />
            </div>
            {onlineTableVisible && (
                <div className="online-controls">
                    <div className="text-right mb10">
                        <span className="pointer" onClick={refreshOnlineLiftingControl}>
                            <RedoOutlined className="mr5" />
                            刷新
                        </span>
                    </div>
                    <Table
                        loading={onlineLoading}
                        dataSource={allOnlineLiftingContol}
                        rowKey={(row) => row.id}
                        columns={onlineColumns}
                        pagination={false}
                        size="small"
                        scroll={{ y: 150 }}
                        bordered
                    />
                </div>
            )}
            <LiftControlEdit
                visible={addModalVisible}
                toggleVisible={setAddModalVisible}
                isEdit={isEdit}
                editLiftControls={allLifitngControl?.control || []}
                areas={areaRef.current?.areas}
                refresh={refreshList}
            />
            <GroupEdit
                visible={groupModalVisible}
                toggleVisible={setGroupModalVisible}
                areas={areaRef?.current?.areas || []}
                selectedArea={selectedArea}
                refresh={refreshList}
            />
            <Modal
                visible={onlineAddModalVisible}
                title="设置"
                onCancel={() => setOnlineAddModalVisible(false)}
                onOk={() => addOnlineLiftControl()}
            >
                <Form form={onlinForm} {...formLayout}>
                    <Form.Item label="设备IP">
                        {selectedOnlineDevice?.ipAddress}
                    </Form.Item>
                    <Form.Item label="设备区域" name="areaId" rules={[{ required: true, message: '请选择区域后添加' }]}>
                        <Select
                            style={{ width: 200 }}
                            allowClear
                        >
                            {areaRef.current?.areas.map((area: IArea) => (
                                <Select.Option key={area.id} value={area.id || -1}>
                                    {area.name}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item label="路桩型号" name="type">
                        <Select disabled>
                            <Select.Option value={0}>{LiftingControlType[0]}</Select.Option>
                            <Select.Option value={1}>{LiftingControlType[1]}</Select.Option>
                            <Select.Option value={2}>{LiftingControlType[2]}</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="在线路桩数" name="onlineNum">
                        <Input disabled />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};
export default AddPile;
